﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace ExcelHelper
{
    public class DataToExcelHelper
    {
        public string DataToExcel(string path)
        {
            try
            {
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                ExcelPackage xlPackage = new ExcelPackage();
                foreach (var sheetData in _data)
                {
                    if (sheetData.Value == null)
                    {
                        continue;
                    }

                    //增加表                    
                    var sheet = xlPackage.Workbook.Worksheets.Add(sheetData.Key);
                    
                    //表头      
                    int col = 1;
                    var itemProps = sheetData.Value.GetType().GetProperties();
                    foreach (var prop in itemProps)
                    {
                        var att = Attribute.GetCustomAttribute(prop, typeof(ColumnAttribute)) as ColumnAttribute;
                        if (att != null)
                        {
                            sheet.Cells[1, col++].Value = att.Name;
                        }
                        else
                        {
                            sheet.Cells[1, col++].Value = prop.Name;
                        }
                    }

                    //数据
                    int row = 2;
                    foreach (var item in sheetData.Value)
                    {
                        col = 1;
                        foreach (var prop in itemProps)
                        {
                            var value = prop.GetValue(item);
                            if (value != null)
                            {
                                sheet.Cells[row, col++].Value = value.ToString();
                            }
                            
                        }

                        //行增加
                        row++;
                    }
                }

                System.IO.FileInfo fileInfo = new System.IO.FileInfo(path);
                xlPackage.SaveAs(fileInfo);

                return null;
            }
            catch(Exception ex)
            {
                return ex.Message;
            }
            
        }

        public void AddSheetData(in IEnumerable<object> sheetData,string sheetName=null)
        {
            if (string.IsNullOrWhiteSpace(sheetName))
            {
                var typeSheetData = sheetData.GetType().GenericTypeArguments[0];
                sheetName = typeSheetData.Name;
            }
            _data.Add(new KeyValuePair<string, IEnumerable<object>>(sheetName,sheetData));
        }

        List<KeyValuePair<string, IEnumerable<object>>> _data = new List<KeyValuePair<string, IEnumerable<object>>>();
        
    }
}
